package net.zoneland.knowledge.utils;

import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import net.zoneland.knowledge.cache.RedisCacheUtil;
import net.zoneland.knowledge.constant.Constants;
import net.zoneland.knowledge.enums.CacheEnum;
import net.zoneland.knowledge.model.LoginUserPojo;
import net.zoneland.knowledge.model.Resource;
import net.zoneland.knowledge.model.Role;
import net.zoneland.knowledge.model.TreeNode;

/**
 * .
 *
 * @author: bcc
 * 2021/6/1
 */
public final class LoginUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginUtils.class);

    /**
     * 根据token获取系统当前登录人
     * @Author Pbody
     * @Date 10:45 2020/3/15
     * @Param []
     * @return net.zoneland.aitalk.dal.bean.User
     **/
    public static LoginUserPojo getCurrentUserByToken(String token) {
        if (StringUtils.isNotBlank(token)) {
            String tokenId = JwtUtil.getTokenId(token);
            if (StringUtils.isNotBlank(tokenId)) {
                Map<String, Object> attrMap = getUserMap(tokenId);
                if (attrMap != null && attrMap.containsKey(Constants.SESSION_ATTRMAP_USER)) {
                    Map userMap = (Map) attrMap.get(Constants.SESSION_ATTRMAP_USER);
                    if (userMap != null && !userMap.isEmpty()) {
                        LoginUserPojo user = GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(userMap), LoginUserPojo.class);
                        return user;
                    }
                }
            }
        }
        return null;
    }
    
    public static List<String> getCurrentUserRoleByToken(String token) {
        if (StringUtils.isNotBlank(token)) {
            String tokenId = JwtUtil.getTokenId(token);
            if (StringUtils.isNotBlank(tokenId)) {
                Map<String, Object> attrMap = getUserMap(tokenId);
                if (attrMap != null && attrMap.containsKey(Constants.SESSION_ATTRMAP_ROEL)) {
                    List<LinkedTreeMap> userRole = (List<LinkedTreeMap>) attrMap.get(Constants.SESSION_ATTRMAP_ROEL);
                    return userRole.stream().map(item -> item.get("roleId").toString()).collect(Collectors.toList());
                }
            }
        }
        return null; 
    }

    /**
     * @Author Pbody
     * @Description 根据token获取系统当前登录人菜单资源信息
     * @Date 10:47 2020/3/15
     * @Param []
     * @return java.util.List<net.zoneland.aitalk.dal.bean.Role>
     **/
    public static List<TreeNode<Resource>> geCurrentResByToken(String token){
        if(StringUtils.isNotBlank(token)){
            String tokenId=JwtUtil.getTokenId(token);
            Map<String, Object> attrMap=getUserMap(tokenId);
            List menuList=(List)attrMap.get(Constants.SESSION_ATTRMAP_MENU);
            List<TreeNode<Resource>> resList = GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(menuList),
                    new TypeToken<List<TreeNode<Resource>>>(){}.getType());
            return resList;
        }
        return null;
    }

    /**
     * 根据tokenId从redis获取用户信息
     * @param tokenId
     * @return Map<String, Object>
     */
    private static Map<String, Object> getUserMap(String tokenId){
        RedisCacheUtil redisCache = SpringContextUtil.getBean(RedisCacheUtil.class);
        String userAttrMap = redisCache.get(CacheEnum.USER_ROLE_CACHE.getValue() + tokenId);
        return GsonUtils.GSON.fromJson(userAttrMap, Map.class);
    }

    /**
     * 是否员工
     * @param employeeNumber
     * @return
     */
    public static boolean isEmployee(final String employeeNumber) {
        if (StringUtils.isBlank(employeeNumber)) {
            return false;
        }
        if (employeeNumber.startsWith("E")
                || employeeNumber.startsWith("22")) {
            return true;
        }
        return false;
    }


    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getServerIp() {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            // 获得本机IP
            String ip = addr.getHostAddress();
            return ip;
        } catch (Exception e) {
            LOGGER.error("服务器IP获取失败");
        }
        return "";
    }
}
